package com.tos.uc.controller;

import com.tos.uc.domain.TosMessageLogs;
import com.tos.uc.domain.TosUser;
import com.tos.uc.domain.User;
import com.tos.uc.service.MessageLogsService;
import com.tos.uc.service.UserService;
import com.tos316.common.utils.UserCacheManager;
import com.tos316.common.utils.httpClientUtils.HttpRequestUtils;
import com.tos316.common.utils.oraginUtils.CommonUtil;
import com.tos316.common.utils.oraginUtils.ObjectUtils;
import com.tos316.common.utils.oraginUtils.ResultUtil;
import com.tos316.common.utils.oraginUtils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by yanfei on 2017/6/27.
 */
@Api(value = "用户中心",description="提供用户信息基本接口")
@RequestMapping("/user/{userId}")
@RestController
public class UserController {

	private static final org.slf4j.Logger Logger = LoggerFactory
			.getLogger(UserController.class);

    @Autowired
    private UserService userService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private MessageLogsService messageLogsService;

	protected final static String TYPE_SNED_SMS = "TYPE_SNED_SMS";

    @PostMapping("/u1")
	@ApiOperation(value = "简单测试接口",  response = User.class,notes = "测试")
    public String getUser(){
        return userService.getUser(1).toString();
    }



	/**
	 //	 * 登录
	 //	 *
	 //	 * @param mphone
	 //	 *            手机号
	 //	 * @param password
	 //	 *            密码
	 //	 * @param code
	 //	 *            验证码
	 //	 * @param type
	 //	 *            类型 0密码登录，1为验证码登录
	 //	 * @return
	 //	 */
	@PostMapping(value = "login")
	@ApiOperation(value = "用户登陆")
	@ResponseBody
	public String login(
			@PathVariable("userId") String userId,
			@RequestParam(value = "mphone") String mphone,
			@RequestParam(value = "password", defaultValue = "") String password,
			@RequestParam(value = "code", defaultValue = "") String code,
			@RequestParam(value = "type", defaultValue = "0") int type) {
		if (type == 0) {// 手机登录
			TosUser user = userService.login(mphone, password);
			if (user == null) {
				return ResultUtil.USER_LOGIN_ERROR();
			}
			return ResultUtil.OK(user);
		} else {// 验证码登录
			TosUser user = userService.loginForCode(mphone, code);
			if (user == null) {
				return ResultUtil.PHONE_CODE_INVALID();
			}
			return ResultUtil.OK(user);
		}
	}

    /**
     //	 * 用户注册
     //	 *
     //	 * @param mphone
     //	 * @param password
     //	 * @param nickname
     //	 * @param code
     //	 *            验证码
     //	 * @param userFrom
     //	 *            用户来源1=>iOS2=>android3=>web4=>weixin5=>other6=>子账号
     //	 * @return
     //	 */
	@PostMapping(value = "register")
    @ApiOperation(value = "用户注册",response = User.class, notes = "返回注册结果", position = 1)
	@ResponseBody
	public String register(@PathVariable(value = "userId",required = false) String userId,
			@RequestParam(value = "mphone") String mphone,
			@RequestParam(value = "password") String password,
			@RequestParam(value = "nickname") String nickname,
			@RequestParam(value = "code",required = false) String code,
			@RequestParam(value = "userFrom") int userFrom) {
		// 验证
		if (!StringUtils.isNotBlank(mphone)
				|| !StringUtils.isNotBlank(password)
				|| !StringUtils.isNotBlank(code)) {
			return ResultUtil.PARAM_ERROR();
		}
		TosUser user = userService.isExistPhone(mphone);
		if (null != user && ObjectUtils.isNotNull(user.getNickname())) {
			return ResultUtil.PHONE_HAD_REGIST();
		}

		TosUser tosUser = userService.isExistNickname(nickname);
		if (null != tosUser) {
			return ResultUtil.PHONE_HAD_NIKENAME();
		}

		TosUser user2 = userService.register(mphone, password, code,
				nickname, userFrom);
		if (null == user2) {
			return ResultUtil.REGIST_ERROR();
		}
		return ResultUtil.OK(user2);
	}


    /**
     * 重置密码
     *
     * @param mphone
     * @param password
     * @param code
     * @return
     */
    @ApiOperation(value = "重置密码",notes = "用户重置密码")
    @RequestMapping(value = "resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public String resetPwd(@PathVariable("userId") String userId,
                           @RequestParam(value = "mphone") String mphone,
                           @RequestParam(value = "password") String password,
                           @RequestParam(value = "code") String code) {
        TosUser tosUser = userService.checkCode(mphone, code);
        if (null != tosUser) {
            int result = this.userService.updateUserPassword(mphone, password);
            return ResultUtil.OK(result);
        } else {
            return ResultUtil.PHONE_CODE_INVALID();
        }

    }


    /**
     * 退出登录
     *
     * @param userId
     * @return
     */
//	@ApiImplicitParam(name="userId", paramType = "query",value = "一个数字a")
	@ApiOperation(value = "退出登录",notes = "退出登录")
    @RequestMapping(value = "{userId}/logout", method = RequestMethod.POST)
    @ResponseBody
    public String logout(@PathVariable("userId") int userId) {

        return ResultUtil.OK();
    }


	/**
	 * 发送短信
	 *
	 * @param mphone
	 * @param type
	 *            验证码类型，0：验证码登录，1：首次注册，2：忘记密码，3：更换手机
	 * @return
	 */
	@ApiOperation(value = "发送短信",response = String.class,notes = "发送短信")
	@RequestMapping(value = "sendMsg", method = RequestMethod.POST)
	@ResponseBody
	public String sendMsg(@PathVariable("userId") int userId,
						  @RequestParam(value = "mphone") String mphone,
						  @RequestParam(value = "type", defaultValue = "0") int type) {
		if (!StringUtils.isNotBlank(mphone)) {
			return ResultUtil.PARAM_ERROR();
		} else if (!CommonUtil.patternPhoneNumber(mphone)) {
			return ResultUtil.PARAM_MATCH_ERROR();
		}

		if (type == 1) {
			boolean bln = userService.checkUserExist(mphone);
			if (bln) {// 判断手机号是否已经被注册
				return ResultUtil.PHONE_HAD_REGIST();
			}
		} else if (type == 2) {
			boolean bln = userService.checkUserExist(mphone);
			if (!bln) {// 判断用户是否存在
				return ResultUtil.USER_NOT_EXIST();
			}
		} else if (type == 3) {
			boolean bln = userService.checkUserExist(mphone);
			if (bln) {// 判断手机号是否已经被注册
				return ResultUtil.PHONE_HAD_REGIST();
			}
			if (userId == 0) {
				return ResultUtil.USER_NOT_EXIST();
			}
		}

		// 检验该手机号码短信发送频率
		boolean b = checkSendMobile(TYPE_SNED_SMS, mphone);
		if (!b) {
			return ResultUtil.SEND_SMS_QUICKLY();
		}
		String ipAddress = HttpRequestUtils.getIpAddr(request);
		Logger.info("源ip地址为：" + ipAddress);
		String codeStr = userService.sendCode(userId, mphone, type);
		TosMessageLogs messageLogs = new TosMessageLogs();
		messageLogs.setMobileNo(mphone);
		messageLogs.setIpAddress(ipAddress);
		messageLogs.setRemark("");
		messageLogs.setCode(codeStr);
		messageLogsService.addMessageLog(messageLogs);
		UserCacheManager.put(TYPE_SNED_SMS, mphone, new Date().getTime());
		return ResultUtil.OK();
	}



	/**
	 * 控制短信发送频率
	 *
	 * @param type
	 * @param mobile
	 * @return
	 */
	private boolean checkSendMobile(String type, String mobile) {
		Object obj = UserCacheManager.getValue(type, mobile);
		if (obj instanceof Long) {
			long time = (Long) obj;
			return System.currentTimeMillis() - time > 1 * 30 * 1000;
		} else {
			return true;
		}
	}
	/**
	 * 短信校验
	 *
	 * @param mphone
	 * @param code
	 * @return
	 */
	@ApiOperation(value = "短信校验", notes = "短信校验")
	@RequestMapping(value = "checkCode", method = RequestMethod.GET)
	@ResponseBody
	public String checkCode(@RequestParam(value = "mphone") String mphone,
							@RequestParam(value = "code") String code) {
		TosUser m = userService.checkCode(mphone, code);

		if (m == null) {
			return ResultUtil.CODE_INVALID();
		}
		return ResultUtil.OK();
	}

	/**
	 * 用户反馈
	 *
	 * @param userId
	 * @param type
	 * @param relateid
	 * @param content
	 * @return
	 */
	@ApiOperation(value = "用户反馈", notes = "用户反馈")
	@RequestMapping(value = "v3/feedback", method = RequestMethod.POST)
	@ResponseBody
	public String addUserFeedback(@PathVariable("userId") int userId,
								  @RequestParam(value = "type") int type,
								  @RequestParam(value = "relateid", defaultValue = "0") int relateid,
								  @RequestParam(value = "content") String content) {
		int id = this.userService.addUserFeedback(type, userId, relateid,
				content);
		return ResultUtil.OK(id);
	}
}
